const query = require('query-mobile-phone-area');
let request = require('request');
let iconv = require('iconv-lite');
const urlUtil = require('./urlUtil');
// require("./ExtString")

async function queryPhone(phone) {
    // {"province":"四川","city":"成都","type":"中国电信"}
    let phoneInfo = query(phone);
    if (phoneInfo == null) {
        console.log('query phone ' + phone + ': 数据库查询失败');
        phoneInfo = await queryPhoneApi(phone);
    } else {
        console.log('query phone ' + phone + ': ' + JSON.stringify(phoneInfo));
    }
    return phoneInfo;
}

function queryPhoneApi(phone) {
    let param = {
        tel: phone,
    };
    return new Promise((resolve, reject) => {
        request.get('https://tcc.taobao.com/cc/json/mobile_tel_segment.htm' + urlUtil.getUrlParam(param),
            {
                rejectUnauthorized: false,
                followRedirect: false,
                encoding: null,
            },
            function (err, response, body) {
                if (!err && response.statusCode == 200) {
                    let bodyDecode = iconv.decode(body, 'gb2312').toString()
                    console.log('res ok: ' + bodyDecode);
                    let result = {province:bodyDecode.getMidText("province:'", "'"),city:"",type:bodyDecode.getMidText("catName:'", "'")};
                    console.log('res ok: ' + JSON.stringify(result));
                    resolve(result);
                } else {
                    console.log('res err: ' + err);
                    reject(err);
                }
            }
        );
    });
}

module.exports = {
    queryPhone
}